import datetime
from datetime import timedelta

from core.celery import celery_app, TaskMonitor
from app.celery_task.models.celery_task import CeleryTask
# from app.service_quality.handlers.qos_host_date_handler import QosHostDateHandler
# from app.service_quality.handlers.qos_host_info_handler import QosHostInfoHandler
from app.service_quality.handlers.qos_host_disk_handler import QosHostDiskHandler
from app.service_quality.handlers.qos_server_date_handler import QosServerDateHandler
from app.service_quality.handlers.qos_server_info_handler import QosServerInfoHandler
from app.service_quality.handlers.qos_traffic_statistics_handler import japi_server_requests, pv_and_uv_agg_query
# from common.elastic import get_es
from common.database import SessionLocal

from core.logger import logger


# @celery_app.task(base=TaskMonitor, bind=True)
# def qos_update_host_info_async(self):
#     """
#     更新主机信息的异步任务
#     """

#     # 获取任务信息
#     tid = self.request.id
#     task_name = self.name.split(".")[-1]
#     session = SessionLocal()

#     # 开始更新告警模板
#     try:
#         # 检查数据库任务信息是否创建
#         result = CeleryTask.check_object_by_tid(session, tid)
#         if not result:
#             logger.error(f"tid:{tid} => progress failed, database info not exist")
#             return False

#         # 更新状态
#         CeleryTask.update_task(session, tid, state="PROGRESS")

#         # 启动任务
#         qos_host_info_handler = QosHostInfoHandler()
#         result = qos_host_info_handler.task_update_host_info_handle(session)
#         if not result:
#             logger.error(f"tid:{tid} => {task_name} failed")
#             return False
#     except Exception as e:
#         logger.exception(f"tid:{tid} => {task_name} error=> {e}")
#         return False
#     finally:
#         session.close()

#     # 更新完成
#     logger.info(f"tid:{tid} => {task_name} success")
#     return True


@celery_app.task(base=TaskMonitor, bind=True)
def qos_update_host_disk_async(self):
    """
    更新磁盘信息的异步任务
    """

    # 获取任务信息
    tid = self.request.id
    task_name = self.name.split(".")[-1]
    session = SessionLocal()

    # 开始更新告警模板
    try:
        # 检查数据库任务信息是否创建
        result = CeleryTask.check_object_by_tid(session, tid)
        if not result:
            logger.error(f"tid:{tid} => progress failed, database info not exist")
            return False

        # 更新状态
        CeleryTask.update_task(session, tid, state="PROGRESS")

        # 启动任务
        qos_host_disk_handler = QosHostDiskHandler()
        result = qos_host_disk_handler.task_update_host_disk_handle(session)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed")
            return False
    except Exception as e:
        logger.exception(f"tid:{tid} => {task_name} error=> {e}")
        return False
    finally:
        session.close()

    # 更新完成
    logger.info(f"tid:{tid} => {task_name} success")
    return True


# @celery_app.task(base=TaskMonitor, bind=True)
# def qos_update_host_date_async(self, data):
#     """
#     更新主机质量数据的异步任务
#     """

#     # 获取任务信息
#     tid = self.request.id
#     task_name = self.name.split(".")[-1]
#     session = SessionLocal()

#     # 开始更新告警模板
#     try:
#         # 检查数据库任务信息是否创建
#         result = CeleryTask.check_object_by_tid(session, tid)
#         if not result:
#             logger.error(f"tid:{tid} => progress failed, database info not exist")
#             return False

#         # 更新状态
#         CeleryTask.update_task(session, tid, state="PROGRESS")

#         # 启动任务
#         qos_host_date_handler = QosHostDateHandler()
#         result = qos_host_date_handler.task_update_host_date_handle(session, data)
#         if not result:
#             logger.error(f"tid:{tid} => {task_name} failed")
#             return False
#     except Exception as e:
#         logger.exception(f"tid:{tid} => {task_name} error=> {e}")
#         return False
#     finally:
#         session.close()

#     # 更新完成
#     logger.info(f"tid:{tid} => {task_name} success")
#     return True


@celery_app.task(base=TaskMonitor, bind=True)
def qos_update_container_server_info_async(self):
    """
    从k8s集群同步容器服务信息的异步任务
    """
    # 获取任务信息
    tid = self.request.id
    task_name = self.name.split(".")[-1]
    session = SessionLocal()

    # 开始更新告警模板
    try:
        # 检查数据库任务信息是否创建
        result = CeleryTask.check_object_by_tid(session, tid)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed, database info not exist")
            return False

        # 更新状态
        CeleryTask.update_task(session, tid, state="PROGRESS")

        # 启动任务
        qos_server_info_handler = QosServerInfoHandler()
        result = qos_server_info_handler.task_update_container_server_info_handle(session)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed")
            return False
    except Exception as e:
        logger.exception(f"tid:{tid} => {task_name} error=> {e}")
        return False
    finally:
        session.close()

    # 更新完成
    logger.info(f"tid:{tid} => {task_name} success")
    return True


@celery_app.task(base=TaskMonitor, bind=True)
def qos_update_server_date_async(self, data):
    """
    更新服务质量数据的异步任务
    """

    # 获取任务信息
    tid = self.request.id
    task_name = self.name.split(".")[-1]
    session = SessionLocal()

    # 开始更新告警模板
    try:
        # 检查数据库任务信息是否创建
        result = CeleryTask.check_object_by_tid(session, tid)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed, database info not exist")
            return False

        # 更新状态
        CeleryTask.update_task(session, tid, state="PROGRESS")

        # 启动任务
        qos_server_date_handler = QosServerDateHandler()
        result = qos_server_date_handler.task_update_server_date_handle(session, data)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed")
            return False
    except Exception as e:
        logger.exception(f"tid:{tid} => {task_name} error=> {e}")
        return False
    finally:
        session.close()

    # 更新完成
    logger.info(f"tid:{tid} => {task_name} success")
    return True


@celery_app.task(base=TaskMonitor, bind=True)
def qos_japi_traffic_statistics_async(self):
    opts = [{"address": "192.168.41.131", "port": "8888", "url": "/_status"},
            {"address": "192.168.41.132", "port": "8888", "url": "/_status"},
            {"address": "192.168.42.227", "port": "8888", "url": "/_status"}]
    res = japi_server_requests(opts)
    if res:
        return True
    else:
        return False


# @celery_app.task(base=TaskMonitor, bind=True)
# def qos_pv_and_uv_traffic_statistics_async(self):
#     search_filters = ["bkv2.wld.net", "japi.wolaidai.com"]
#     now = datetime.datetime.now()
#     cst_begin_time = (now - datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0).strftime("%Y-%m-%d %H:%M:%S")
#     cst_end_time = (now - datetime.timedelta(days=1)).replace(hour=23, minute=59, second=59, microsecond=59).strftime("%Y-%m-%d %H:%M:%S")
#     index = 'logstash-openresty_access*'
#     es = get_es()
#     res = pv_and_uv_agg_query(es_client=es, index=index, cst_begin_time=cst_begin_time, cst_end_time=cst_end_time,
#                               search_filters=search_filters)
#     if res:
#         return True
#     else:
#         return False


if __name__ == '__main__':
    pass
